package com.fouram.minio.util;

import cn.hutool.extra.spring.SpringUtil;
import io.minio.*;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * minio工具类
 * @author liup
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MinioUtils {

    private static final MinioClient client = SpringUtil.getBean(MinioClient.class);

    @SneakyThrows
    public static void createBucketIfAbsent(String bucketName) {
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
        if (!client.bucketExists(bucketExistsArgs)) {
            MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();
            client.makeBucket(makeBucketArgs);
        }
    }

    /**
     * 上传文件
     * @param bucketName
     * @param objectName
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static String putObject(String bucketName, String objectName, InputStream inputStream, String suffix) throws Exception {
        String contentType = choose(suffix.toUpperCase());
        createBucketIfAbsent(bucketName);
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .contentType(contentType)
                .stream(inputStream, inputStream.available(), -1)
                .build();
        client.putObject(putObjectArgs);
        String path = client.getObjectUrl(bucketName, objectName);
        return path;
    }

    private static String choose(String suffix) {
        String contentType = "";
        switch (suffix){
            case "JPG":
                contentType = "image/jpg";
                break;
            case "GIF":
                contentType = "image/gif";
                break;
            case "JPEG":
                contentType = "image/jpeg";
                break;
            case "PNG":
                contentType = "image/png";
                break;
            case "PDF":
                contentType = "application/pdf";
                break;
            default:
                contentType = "*/*";
        }
        return contentType;
    }

    /**
     * 删除文件
     * @param bucketName
     * @param objectName
     * @throws Exception
     */
    public static void removeObject(String bucketName, String objectName) throws Exception {
        RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build();
        client.removeObject(removeObjectArgs);
    }
}
